package com.mdd.front.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.mdd.common.constant.GlobalConstant;
import com.mdd.common.core.PageResult;
import com.mdd.common.entity.salesman.Salesman;
import com.mdd.common.entity.salesman.UserSalesman;
import com.mdd.common.exception.OperateException;
import com.mdd.common.mapper.salesman.SalesmanMapper;
import com.mdd.front.LikeFrontThreadLocal;
import com.mdd.front.service.salesman.IUserSalesmanService;
import com.mdd.front.validate.PageParam;
import com.mdd.front.validate.salesman.UserSalesmanParam;
import com.mdd.front.vo.salesman.UserSalesmanDetailVo;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Objects;

@RestController
@RequestMapping("/api/userSalesman")
public class UserSalesmanController {

	@Resource
	private IUserSalesmanService iUserSalesmanService;

	@Resource
	private SalesmanMapper salesmanMapper;

	@Resource
	private IUserSalesmanService userSalesmanService;

	@GetMapping("/{userId}")
	public void addUserSalesman(@PathVariable("userId") Integer userId) {
		Integer user = LikeFrontThreadLocal.getUserId();
		QueryWrapper<Salesman> salesmanQueryWrapper = new QueryWrapper<>();
		salesmanQueryWrapper.eq("user_id", userId);
		salesmanQueryWrapper.eq("is_delete", 0);
		// 查询是不是存在该推销员
		Salesman salesman = salesmanMapper.selectOne(salesmanQueryWrapper);
		Assert.notNull(salesman, "推销员错误！！！");

		LambdaUpdateWrapper<UserSalesman> updateWrapper = new LambdaUpdateWrapper<>();
		updateWrapper.eq(UserSalesman::getUserId, user);
		updateWrapper.eq(UserSalesman::getIsDelete, GlobalConstant.NOT_DELETE);
		UserSalesman one = userSalesmanService.getOne(updateWrapper);
		if(Objects.nonNull(one)){
			throw new OperateException("已绑定优惠码");
		}
		UserSalesmanParam userSalesman = new UserSalesmanParam();
		userSalesman.setUserId(user);
		userSalesman.setSalesmanId(salesman.getId());
		// 将推销员跟用户进行绑定
		iUserSalesmanService.add(userSalesman);
	}

		@GetMapping("/getUserDetail")
	public PageResult<UserSalesmanDetailVo> getUserDetail(@Validated PageParam pageParam){
		Integer userId = LikeFrontThreadLocal.getUserId();
		return iUserSalesmanService.getUserDetail(userId, pageParam);
	}
}
